﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Wabo.Util
{
    public class Crypto
    {
        public static string Sha1(string data)
        {
            var sha1 = SHA1.Create();           
            byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));
            var returnValue = new StringBuilder();

            //loop for each byte and add it to StringBuilder
            for (int i = 0; i < hashData.Length; i++)
            {
                returnValue.Append(hashData[i].ToString());
            }
            return returnValue.ToString();
        }

        public static bool ValidateSha1(string inputData, string storedHashData)
        {            
            string getHashInputData = Sha1(inputData);
            return (string.Compare(getHashInputData, storedHashData) == 0);
        }

        public static string Md5(string data)
        {
            var md5 = MD5.Create();
            byte[] hashData = md5.ComputeHash(Encoding.Default.GetBytes(data));

            var returnValue = new StringBuilder();
            
            for (int i = 0; i < hashData.Length; i++)
            {
                returnValue.Append(hashData[i].ToString());
            }

            
            return returnValue.ToString();

        }

        private bool ValidateMd5(string inputData, string storedHashData)
        {            
            string getHashInputData = Md5(inputData);
            return (string.Compare(getHashInputData, storedHashData) == 0);
        }

        public static string GetSaltedWord( string salt, string password)
        {
            return String.Format("{0}/{1}/{2}",salt,password,salt);
        }

        public static string GenerateSalt()
        {
            return Md5(DateTime.Now.ToString()).Substring(1, 10);
        }

        public static string Base64Encode(string toEncode)
        {
            byte[] toEncodeAsBytes = Encoding.Unicode.GetBytes(toEncode);
            string returnValue = Convert.ToBase64String(toEncodeAsBytes);
            return returnValue;
        }

        public static string Base64Decode(string encodedData)
        {
            byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData);
            string returnValue = Encoding.Unicode.GetString(encodedDataAsBytes);
            return returnValue;
        }
    }
}
